define(function(require, exports, module) {
	var $ = require('$'),
      _ = require('underscore'),
      Backbone = require('backbone'),
      AV = require('leancloud');

	module.exports = Backbone.View.extend({
		el: '.login-screen',
		events: {
			'click .login-button': 'onLogin',
			'click .login-doubt-button': 'onDoubt',
			'click .login-newuser-button': 'onNewUser'
		},
		template: require('tpl/sign-in.html'),
		initialize: function(options) {
			var self = this;
			this.gomac = options.gomac;

			//初始化视图
			this.$el.html(this.template);

			this.form = this.$el.find('.login-form');

      this.$el.on('closed', function(e) { self.undelegateEvents(); });
		},
		onLogin: function(e) {
			var self = this;
			//获取表单数据
			var data = self.gomac.formToJSON(self.form);

      if(_.isEmpty(data.username) || _.isEmpty(data.password)) {
          self.gomac.alert('帐号或密码不能为空');
      }
      else {
      		//self.gomac.alert('你好, '+data.username);
          AV.User.logIn(data.username, data.password, {
              success: function(user) {
                console.log('登录成功', user);
                self.gomac.mainView.router.loadPage('pages/home.html');
                self.gomac.closeModal(self.$el);
              },
              error: function(user, error) {
                console.log('登录失败', user, error);
                self.gomac.alert(error.message, '出错：'+error.code);
              }
          });
      }
		},
		onDoubt: function(e) {
			var self = this,
			    group = [];

      group.push([{
          text: '找回密码',
          onClick: function(event) {
              //TODO: 
              self.gomac.alert('密码已找回');
          }
      }, {
          text: '短信验证登录',
          onClick: function(event) {
              //TODO: 
              self.gomac.alert('已发送短信到您的手机上');
          }
      }]);

      group.push([{
          text: '取消',
          color: 'red'
      }]);
      
      self.gomac.actions(group);
		},
		onNewUser: function(e) {
			var self = this;
			//TODO: 
			self.gomac.mainView.router.loadPage('pages/home.html');
      self.gomac.closeModal(self.$el);
		}
	});
});